//
//  NSString+HXDES.m
//  24_加密
//
//  Created by 徐昊 on 16/8/16.
//  Copyright © 2016年 徐昊. All rights reserved.
//

#import "NSString+HXDES.h"
#import <CommonCrypto/CommonCrypto.h>
#define key @"01234567"
static Byte iv[] = {1, 2, 3, 4, 5, 6, 7, 8};
@implementation NSString (HXDES)
- (NSString *)stringWithDES {
    // 1. 将字符串本身转换成C字符串
    const char *string = [self UTF8String];
    // 2. 接受容器
    unsigned char byte[1024];
    // 3. 接受容器大小
    size_t dataOutMoved = 0;
    // 4. DES加密过程
    /** 
     * 参数1: 加密/解密
     * 参数2: 加密/解密 方式
     * 参数3: 分组密码的选项
     * 参数4: 密钥
     * 参数5: 密钥的大小
     * 参数6: 向量
     * 参数7: C的字符串
     * 参数8: 字符串长度 length
     * 参数9: 接受容器
     * 参数10: 容器大小
     * 参数11: 容器的最终个数
     */
    CCCryptorStatus cryptorStastus = CCCrypt(kCCEncrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding, [key UTF8String], kCCKeySizeDES, iv, string, strlen(string), byte, 1024, &dataOutMoved);
    // 5. 判断是否成功
    if (cryptorStastus == kCCSuccess) {
        NSData *desData = [NSData dataWithBytes:byte length:dataOutMoved];
        // 转成字符串 -- Base64返回
        NSString *desBaseString = [desData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        return desBaseString;
    } else {
        NSLog(@"加密失败");
        return  nil;
    }
}
- (NSString *)DESWithString {
    NSData *base64Data = [[NSData alloc] initWithBase64EncodedString:self options:NSDataBase64DecodingIgnoreUnknownCharacters];
    const void *byte = base64Data.bytes;
    size_t dataOutMoved = 0;
    unsigned char buffer[1024];
    CCCryptorStatus cryptorStastus = CCCrypt(kCCDecrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding, [key UTF8String], kCCKeySizeDES, iv, byte, [base64Data length], buffer, 1024, &dataOutMoved);
    if (cryptorStastus == kCCSuccess) {
        NSData *sourceData = [[NSData alloc] initWithBytes:buffer length:dataOutMoved];
        NSString *sourceString = [[NSString alloc] initWithData:sourceData encoding:NSUTF8StringEncoding];
        NSLog(@"解码成功");
        NSLog(@"%@", sourceString);
        return sourceString;
    } else {
        NSLog(@"解码失败");
        return nil;
    }
}
@end
